using System.Threading.Tasks;
using Volo.Abp.BackgroundJobs;

namespace Xms.Abp.Emailing;

/// <summary>
/// This class can be used as base to implement <see cref="IEmailSender"/>.
/// </summary>
public abstract class EmailSenderBase : IEmailSender
{
    protected IBackgroundJobManager BackgroundJobManager { get; }

    /// <summary>
    /// Constructor.
    /// </summary>
    protected EmailSenderBase(
        IBackgroundJobManager backgroundJobManager)
    {
        BackgroundJobManager = backgroundJobManager;
    }

    public virtual async Task SendAsync(EmailMessage emailMessage)
    {
        await SendEmailAsync(emailMessage);
    }

    public virtual async Task QueueAsync(EmailMessage emailMessage)
    {
        if (!BackgroundJobManager.IsAvailable())
        {
            await SendAsync(emailMessage);
            return;
        }
        await BackgroundJobManager.EnqueueAsync(emailMessage);
    }

    /// <summary>
    /// Should implement this method to send email in derived classes.
    /// </summary>
    /// <param name="mail">Mail to be sent</param>
    protected abstract Task SendEmailAsync(EmailMessage emailMessage);
}
